//
//  COBaseTabbarController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/7.
//

import UIKit

//TabBarButton中 图片与文字上下所占比
private var xscale = 0.80;
private var nxscale = 0.65;

private var requestTimeOut: Double = 30
//title默认颜色
private var TitleColor = UIColor.gray
//title字体大小
private var TitleFontSize = 12
//TabBar背景色
private var TabBarBackgroundColor = UIColor.clear
//数字角标直径
private var NumMark_W_H = 20
//小红点直径
private var PointMark_W_H = 15
//title选中颜色
private var TitleColor_Sel =  UIColor(red: 41.0 / 255.0, green: 167.0 / 255.0, blue: 245.0 / 255.0, alpha: 1)

class COTabbarBtn: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.imageView?.contentMode = .scaleAspectFit
        self.titleLabel?.textAlignment = .center
        self.backgroundColor = UIColor.clear
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
        let newX = 0.0
        let newY = KisPhoneX() ? 5.0:0.0
        let newWidth = contentRect.size.width
        let newHeight = contentRect.size.height*(KisPhoneX() ? xscale:nxscale)-newY
        return CGRectMake(newX, newY, newWidth, newHeight)
    }
    
    override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
        let newX = 0.0
        let newY = contentRect.size.height*(KisPhoneX() ? xscale:nxscale)
        let newWidth = contentRect.size.width
        let newHeight = contentRect.size.height - contentRect.size.height*(KisPhoneX() ? xscale:nxscale)
        return CGRectMake(newX, newY, newWidth, newHeight)
    }
}

class COBaseTabbarController: UITabBarController {
    
    var controllerArray = [String]()
    var imageArray      = [String]()
    var selImageArray   = [String]()
    var tabBarHeight    = 0.0
    var tabBarView      = UIView()
    var seleBtn         = UIButton()
    
    // 计时器
    private var randomVideoTime: COCallTimeTool!
    var count:Int! = 0
    
    weak var newUserOnlyView:CONewerDragView?
    
    lazy var bindAlertView: COEmailBindAlert = {
        let bind = COEmailBindAlert(frame: CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT))
        return bind
    }()
    
    lazy var welcomeBackView: COWelcomeBackAlert = {
        let bind = COWelcomeBackAlert(frame: CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT))
        return bind
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.controllerArray = ["COHotMainController","CORankMainController","COConversationListController","COMineMainController"]
        self.imageArray      = ["coco_tabbar_normal00","coco_tabbar_normal01","coco_tabbar_normal02","coco_tabbar_normal03"]
        self.selImageArray   = ["coco_tabbar_select00","coco_tabbar_select01","coco_tabbar_select02","coco_tabbar_select03"]
        self.initTabBar()
    }
    
    func initTabBar(){
        //处理tabbar顶部黑线问题
        clearLineView()
        //创建VC
        createControllerWithControllerArray(self.controllerArray)
        //创建tabBarView
        createTabBarView()
        //设置TabbarLine
        setTabBarShadowLine()
        //设置绑定以及通知
        addNotiWithBind()
    }
    
    //处理tabbar顶部黑线问题
    func clearLineView(){
        if #available(iOS 13.0, *) {
            let appearnce = UITabBarAppearance()
            appearnce.configureWithTransparentBackground()
            appearnce.backgroundColor = UIColor.clear
            appearnce.shadowImage = UIImage()
            self.tabBar.standardAppearance = appearnce
            if #available(iOS 15.0, *) {
                self.tabBar.scrollEdgeAppearance = appearnce
            }
        } else {
            self.tabBar.shadowImage = UIImage()
            self.tabBar.backgroundImage = UIImage()
        }
    }

    //创建VC
    func createControllerWithControllerArray(_ controllers:[String]){
        if(controllers.count == 0) {print("控制器数组为nil,请初始化")}
        let tabbarArr = NSMutableArray()
        let projectName = Bundle.main.infoDictionary?["CFBundleName"] as! String
        for i in 0..<controllers.count{
            //类   通过NSClassFromString方法创建类，类的字符串为：工程名 + “.” + 类名
            let cls = NSClassFromString(projectName + "." + controllers[i]) as! UIViewController.Type
            //创建控制器对象
            let viewController = cls.init()
            //创建导航控制器
            let nav = COBaseNavigationController(rootViewController: viewController)
            //添加子控制器
            tabbarArr.add(nav)
        }
        self.viewControllers = (tabbarArr as! [UIViewController])
    }
    
    //创建tabBarView
    func createTabBarView(){
        if (self.tabBarHeight < 49.0){
            self.tabBarHeight = 49.0
        }
        self.tabBarView = UIView(frame: CGRectMake(0, 0, SCREENWIDTH, KTabBarAndSafeHeight))
        self.tabBarView.backgroundColor = UIColor.clear
//        if #available(iOS 11.0, *) {
//            // 设置 左上 右上 圆角
//            self.tabBarView.layer.cornerRadius = 20.0
//            self.tabBarView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
//        }
        self.tabBar.addSubview(self.tabBarView)
        let num = self.controllerArray.count
        for i in 0..<num {
            let width = Float(SCREENWIDTH)/Float(num) * Float(i)
            let widthX = (Float(SCREENWIDTH)/Float(num)-44.0)/2.0
            let button = COTabbarBtn(frame: CGRectMake(CGFloat(width + widthX), KisPhoneX() ? 14.0:8.0, 44.0, 44.0))
            button.tag = 1000+i
            //常态文字颜色
            button.setTitleColor(TitleColor, for: .normal)
            //选中文字颜色
            button.setTitleColor(TitleColor_Sel, for: .selected)
            button.titleLabel?.font = UIFont.systemFont(ofSize: CGFloat(TitleFontSize))
            button.setImage(UIImage(named: self.imageArray[i]), for: .normal)
            button.setImage(UIImage(named: self.selImageArray[i]), for: .selected)
            button.setTitle("", for: .normal)
            button.addTarget(self, action: #selector(buttonAction(button:)), for: .touchUpInside)
            self.tabBarView.addSubview(button)
            if (i == 0){
                //默认选中
                button.isSelected = true
                self.seleBtn = button
            }
            let numLabel = UILabel(frame: CGRectMake(button.frame.size.width/2.0+10, 0, CGFloat(NumMark_W_H), CGFloat(NumMark_W_H)))
            numLabel.layer.masksToBounds = true
            numLabel.layer.cornerRadius = 10.0
            numLabel.backgroundColor = UIColor.red
            numLabel.textColor = UIColor.white
            numLabel.textAlignment = .center
            numLabel.font = UIFont.systemFont(ofSize: 12.0)
            numLabel.tag = 1010+i
            numLabel.isHidden = true
            button.addSubview(numLabel)
        }
    }
    
    @objc func buttonAction(button:UIButton) {
        let index = button.tag - 1000
        self.showController(with: index)
    }
    
    func showController(with index:NSInteger){
        if (index >= self.controllerArray.count){
            print("index取值超出范围")
            return
        }
        self.seleBtn.isSelected = false
        let button = self.tabBarView.viewWithTag(1000+index) as! UIButton
        button.isSelected = true
        self.seleBtn = button
        self.selectedIndex = index
    }
    
    //设置tabbarView圆角
    func setTabBarShadowLine(){
        self.tabBarView.layer.masksToBounds = false
        let originImage = UIColor.colorWithHex("#FFFFFF", 0.3).toImage()
        let resizeImage = UIImage.resizeWithStretchImage(originImage!)
        self.tabBarView.layer.contents = resizeImage.cgImage
        self.tabBarView.clipsCorners(corners: [.topLeft, .topRight], radius: 20)
    }
    
    // 数字角标
    public func showBadgeMark(_ badge:NSInteger,_ index:NSInteger){
        if (index >= self.controllerArray.count){
            print("index取值超出范围")
            return
        }
        let numLabel = self.tabBarView.viewWithTag(1010+index) as! UILabel
        numLabel.isHidden = false
        var nFrame = numLabel.frame
        if (badge <= 0){
            //隐藏角标
           hideMarkIndex(index)
        }else{
            if(badge > 0 && badge <= 9){
                nFrame.size.width = CGFloat(PointMark_W_H)
            }else if(badge > 0 && badge <= 9){
                nFrame.size.width = CGFloat(PointMark_W_H)+5.0
            }else{
                nFrame.size.width = CGFloat(PointMark_W_H)+10.0
            }
            nFrame.size.height = CGFloat(PointMark_W_H)
            numLabel.frame = nFrame
            numLabel.layer.cornerRadius = CGFloat(PointMark_W_H)/2.0
            numLabel.text = String(badge)
            if (badge>99){
                numLabel.text = "99+"
            }
        }
    }
    
    //小红点
    public func showPointMarkIndex(_ index:NSInteger){
        if (index >= self.controllerArray.count){
            print("index取值超出范围")
            return
        }
        let numLabel = self.tabBarView.viewWithTag(1010+index) as! UILabel
        numLabel.isHidden = false
        var nFrame = numLabel.frame
        nFrame.size.height = CGFloat(PointMark_W_H)
        nFrame.size.width = CGFloat(PointMark_W_H)
        numLabel.frame = nFrame
        numLabel.layer.cornerRadius = CGFloat(PointMark_W_H)/2.0
        numLabel.text = ""
    }
    
    //隐藏指定位置角标
    public func hideMarkIndex(_ index:NSInteger){
        if (index >= self.controllerArray.count){
            print("index取值超出范围")
            return
        }
        let numLabel = self.tabBarView.viewWithTag(1010+index) as! UILabel
        numLabel.isHidden = true
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension COBaseTabbarController{
    
    func addNotiWithBind(){
        NotificationCenter.default.addObserver(self, selector: #selector(showNewUserAlertView), name: .NewUserRechargeNotification, object: nil)
        showNewUserAlertView(noti: nil)
        
        randomVideoTime = COCallTimeTool.scheduledTimer(timeInterval: 1, target: self, selector: #selector(randomTime), userInfo: nil, repeats: true)
        randomVideoTime.fire()
        // 随机电话计时器
        NotificationCenter.default.addObserver(self, selector: #selector(randomTimeRun), name: .RandomTimeRunNotification, object: nil)
        // 倒计时关闭打开
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.willEnterForegroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(quitAppTimeStop), name: .QuitAppTimeStopNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(checkBindFree), name: .kIsNeedBindEmail, object: nil)
        kvTrackerAction()
        marketingUpAcrion()
        welcomeToBack()
    }
    
    //MARK: -------------- 倒计时运行 ----------------
    @objc private func didBecomeActive(noti: Notification) {
        guard let _ = randomVideoTime else {
            return
        }
        //继续
        randomVideoTime.fireDate = NSDate.init() as Date
        randomVideoTime.fireDate = Date.distantPast
    }
    
    @objc private func enterBackground(noti: Notification) {
        guard let _ = randomVideoTime else {
            return
        }
        //暂停
        randomVideoTime.fireDate = Date.distantFuture
    }
    
    //MARK: -------------- 随机电话拨打接听状态 ----------------
    @objc private func randomTimeRun(noti: Notification) {
        let userInfo = noti.userInfo
        if (userInfo != nil) {
            let type: Int = userInfo!["type"] as! Int
            if (type == 1){
                guard let _ = randomVideoTime else {
                    return
                }
                //暂停
                randomVideoTime.fireDate = Date.distantFuture
            }else{
                guard let _ = randomVideoTime else {
                    return
                }
                //继续
                randomVideoTime.fireDate = NSDate.init() as Date
                randomVideoTime.fireDate = Date.distantPast
            }
        }
    }
    
    //MARK: -------------- 退出登录关闭倒计时 ----------------
    @objc private func quitAppTimeStop(noti: Notification) {
        deinitrandomVideoTimer()
    }
    
    //MARK: -------------- 自动挂断 ----------------
    @objc func randomTime(){
        count += 1
//        print("randomTime ---  \(count!)")
        if (count == 10 || count == 20 || count == 35 || count == 55 || count == 80){
            self.requestVideoTalk()
        }
        if (count > 80){
            deinitrandomVideoTimer()
        }
    }
    
    // 移除计时器
    func deinitrandomVideoTimer(){
        guard let _ = randomVideoTime else {
            return
        }
        randomVideoTime.invalidate()
        randomVideoTime = nil
    }
    
    func requestVideoTalk(){
        let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
        let liveaclling = kLiveCalling.keyGetNSDefaultsKey() as? Bool
        if feed == true || liveaclling == true { return }
        if COChatMsgManager.shared.callViewController != nil { return }
        if (self.currentController != nil){
            if (self.currentController!.isKind(of: COCallViewController.self)){
                return
            }
        }
        COHttpManager.request(target: COBaseApi.electionTen, modelType: ElectionResponseModel.self) { code, object, success in
            if (success == true){
                let model = object?.worksResponse
                if (model?.streamerId.isEmptyStr == true || model?.streamerName.isEmpty == true){
                    return
                }
                let call = COCallViewController()
                var usrModel = DGChatUserInfoModel()
                usrModel.profilePhoto = model!.aliWorksUrl
                usrModel.name = model!.streamerName
                usrModel.streamerId = model!.streamerId
                usrModel.price = model!.price
                usrModel.rongUserId = model!.rongyunId
                usrModel.summary = model!.summary
                call.anchorModel = usrModel
                kLiveCalling.keySaveToNSDefaults(with: true)
                UIToolHelper.currentViewController()?.navigationController?.pushViewController(call, animated: true)
            }
        } failureBlock: { code, msg in
        }
    }
    
    func kvTrackerAction(){
        COKVATrackerManager.shared().kvaTracker { channel in
            if (COKVATrackerManager.shared().firstChar(channel) == "K" || COKVATrackerManager.shared().firstChar(channel) == "S"){
                var params = [String:Any]()
                params["siteId"] = channel
                COHttpManager.request(target: COBaseApi.kvaKol(param: params), modelType: CONSObjectModel.self) { code, object, success in
                } failureBlock: { code, msg in
                }
            }else{
                var params = [String:Any]()
                params["channelId"] = channel
                COHttpManager.request(target: COBaseApi.kvaChannel(param: params), modelType: CONSObjectModel.self) { code, object, success in
                } failureBlock: { code, msg in
                }
            }
        }
    }
    
    //MARK: -------------- 新人优惠是否展示 ----------------
    @objc private func showNewUserAlertView(noti: Notification?) {
        let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
        if feed == true {
            return
        }
        if (self.newUserOnlyView != nil){
            self.newUserOnlyView?.removeFromSuperview()
            self.newUserOnlyView = nil
        }
        if (noti != nil){
            let userInfo = noti!.userInfo
            let type: Int = userInfo!["type"] as! Int
            if (type == 1){
                if (self.newUserOnlyView != nil){
                    self.newUserOnlyView?.removeFromSuperview()
                    self.newUserOnlyView = nil
                }
                return
            }
        }
        var params = [String:Any]()
        params["platform"]  = 2
        params["uuid"]  = HDeviceIdentifier.deviceIdentifier()
        COHttpManager.request(target: COBaseApi.popupsPrice(param: params), modelType: COPopupsPriceModel.self) {[weak self] code, object, success in
            if (success == true){
                let models = object?.response
                if (models?.count ?? 0 > 0){
                    if (UIToolHelper.currentViewController() != nil){
                        if ((UIToolHelper.currentViewController()!.isKind(of: COBalanceController.self)) || UIToolHelper.currentViewController()!.isKind(of: COCallViewController.self)){
                            if (self?.newUserOnlyView != nil){
                                self?.newUserOnlyView?.removeFromSuperview()
                                self?.newUserOnlyView = nil
                            }
                            return
                        }
                    }
                    let newuse = CONewerDragView()
                    self?.view.addSubview(newuse)
                    newuse.snp.makeConstraints({ make in
                        make.size.equalTo(CGSizeMake(PTW(82), PTW(140)))
                        make.right.equalToSuperview()
                        make.bottom.equalToSuperview().offset(-PTW(40)-KTabBarAndSafeHeight)
                    })
                    self?.newUserOnlyView = newuse
                    newuse.addTap { ges in
                        let recharge = CONewserRechargeAlert(with: models!.first!)
                        recharge.show()
                        recharge.callBolck = { [weak self] in
                            self?.rechargeAction(model: models!.first!)
                        }
                    }
                }
            }
        } failureBlock: { code, msg in
        }
    }
    
    func rechargeAction(model:COBalanceModel){
        UIToolHelper.showHUD()
        AppPurchaseManager.pay(purchaseProductId: model.productId!) { result in
            UIToolHelper.hideHUD()
            if (result == true){
                AppPurchaseManager.updateBalance()
                if (self.newUserOnlyView != nil){
                    self.newUserOnlyView?.removeFromSuperview()
                    self.newUserOnlyView = nil
                }
            }
        }
    }
    
    // 版本更新
    func marketingUpAcrion(){
        COHttpManager.request(target: COBaseApi.marketUpdate, modelType: MarketResponseModel.self) { code, object, success in
            let model = object?.response
            if (model?.link.isEmptyStr == false){
                NotificationCenter.default.post(name: .kMarketingUpNoti, object: model!.toJSONString())
            }else{
                print("没有更新版本")
            }
        } failureBlock: { code, msg in
            print("\(msg ?? "")")
        }
    }
    
    // 欢迎回归
    func welcomeToBack(){
        COHttpManager.request(target: COBaseApi.bindFree, modelType: CONSObjectModel.self) {[weak self] code, object, success in
            if (success == true){
                self?.welcomeBackView.showInView(nil)
            }
        } failureBlock: { code, msg in
        }
    }
    
    @objc private func checkBindFree(noti: Notification) {
        let model = COUserInfoManager.shared.curUser
        if (model?.userResponse.email.isEmptyStr == false){
            return
        }
        self.bindAlertView.showInView(nil)
    }
}
